package com.three.box.activity

import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.view.ViewGroup
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.recyclerview.widget.DividerItemDecoration
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter4.BaseQuickAdapter
import com.chad.library.adapter4.viewholder.QuickViewHolder
import com.three.box.R
import com.three.box.base.BaseActivity
import com.three.box.databinding.ActivityRecordListBinding
import com.three.box.entity.ApiResult
import com.three.box.entity.ApiResultList
import com.three.box.entity.BoxRecord
import com.three.box.network.kt.ApiServiceFactory
import com.three.box.network.kt.AppApiService
import com.three.box.network.kt.AppHost
import retrofit2.Call
import retrofit2.Callback
import retrofit2.Response

class RecordListActivity : BaseActivity() {

    companion object {
        const val TAG = "RecordListActivity"
    }

    private lateinit var binding: ActivityRecordListBinding

    private lateinit var recordAdapter: RecordAdapter

    private lateinit var resultLaunch: ActivityResultLauncher<Intent>
    private var recordList = mutableListOf<BoxRecord>()

    private var boxId = -1

    override fun onCreate(savedInstanceState: Bundle?) {
        binding = ActivityRecordListBinding.inflate(layoutInflater)
        setStatusBar()
        super.onCreate(savedInstanceState)

        boxId = intent.getIntExtra("box_id", -1)

        initView()

        orderList()

        resultLaunch = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) { activityResult ->
            // 获取到Activity回传的数据
            if(activityResult.resultCode != Activity.RESULT_OK) {
                return@registerForActivityResult
            }
//            val data = activityResult.data
//            val resultList: ArrayList<Product>? = if (Build.VERSION.SDK_INT <  Build.VERSION_CODES.TIRAMISU)
//                data?.getParcelableArrayListExtra("product_list")
//            else
//                data?.getParcelableArrayListExtra("product_list", Product::class.java)
            setResult(RESULT_OK, activityResult.data)
            finish()
        }
    }

    override fun getLayoutView() = binding.root

    private fun initView() {
        binding.backIv.setOnClickListener { finish() }
        recordAdapter = RecordAdapter()
        with(binding.recyclerView) {
            layoutManager = LinearLayoutManager(context).apply { orientation = androidx.recyclerview.widget.RecyclerView.VERTICAL }
            addItemDecoration(DividerItemDecoration(this@RecordListActivity, DividerItemDecoration.VERTICAL))
            adapter = recordAdapter
        }
        recordAdapter.setOnItemClickListener { adapter, _, position ->
            val record = adapter.getItem(position)
            val intent = Intent(this, RecordInfoActivity::class.java)
            intent.putExtra("record_id", record?.id)

            resultLaunch.launch(intent)
        }
        recordAdapter.submitList(recordList)
    }

    inner class RecordAdapter : BaseQuickAdapter<BoxRecord, QuickViewHolder>() {
        override fun onCreateViewHolder(context: Context, parent: ViewGroup, viewType: Int): QuickViewHolder {
            // 返回一个 ViewHolder
            return QuickViewHolder(R.layout.item_record_list, parent)
        }

        override fun onBindViewHolder(holder: QuickViewHolder, position: Int, item: BoxRecord?) {
            holder.setText(R.id.operate_time_tv, getString(R.string.format_operate_time, item?.time))
            holder.setText(R.id.operator_tv, getString(R.string.format_operate_name, item?.userInfo?.username))
            holder.setText(R.id.operator_type_tv, getString(R.string.format_operate_type, item?.operateTypeInfo?.name ?: "无"))
            holder.setText(R.id.note_tv, getString(R.string.format_note, item?.notes ?: "无"))
        }
    }

    private val service = ApiServiceFactory.createAPIService(AppHost.AppApi, AppApiService::class.java)
    private fun orderList() {
        val call = service.orderList(boxId, 1, 100)
        call.enqueue(object : Callback<ApiResultList<BoxRecord>> {
            override fun onResponse(
                call: Call<ApiResultList<BoxRecord>>,
                response: Response<ApiResultList<BoxRecord>>
            ) {
                val apiResult = response.body()
                if (apiResult?.errno == ApiResult.SUCCESS) {
                    val list = apiResult.data.data
                    recordList.clear()
                    recordList.addAll(list)
                    recordAdapter.addAll(recordList)
                } else {
                    Log.d(TAG, "error, ${apiResult?.errmsg}")
                }
            }

            override fun onFailure(call: Call<ApiResultList<BoxRecord>>, t: Throwable) {
                t.printStackTrace()
            }
        })
    }
}